    //
//  UPStartViewController.mm
//  UPai
//
//  Created by zhan ky on 11-10-9.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "UPStartViewController.h"
#import "PicCardView.h"
#import "UPaiAppDelegate.h"

#define RectBottomView	CGRectMake(0, 460-44-44, 320, 44)
#define RectRegisterBtn	CGRectMake(160-60, 460-44-44+4, 50, 36)
#define RectLoginBtn	CGRectMake(160+10, 460-44-44+4, 50, 36)

#define PIC_CNT_DEFAULT	18
#define XMargin 4
#define YMargin 4


@implementation UIImage(rescaleImageToSize)
- (UIImage *)rescaleImageToSize:(CGSize)size 
{
	CGRect rect = CGRectMake(0.0, 0.0, size.width, size.height);
	UIGraphicsBeginImageContext(rect.size);
	[self drawInRect:rect];  // scales image to rect
	
	UIImage *resImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	
	return resImage;
}
@end



@implementation UPStartViewController
@synthesize m_scrollView,m_bottomView,m_refreshSpinner;
@synthesize m_timerForSpinner;
@synthesize m_registViewCtrl,m_loginViewCtrl;
@synthesize m_imgArray;
// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

- (void)stopRefreshAnimating
{
	if (m_refreshSpinner.isAnimating) 
	{
		[self.m_refreshSpinner stopAnimating];
		[m_refreshSpinner release];
		m_refreshSpinner = nil;
		
		//按钮相关设置
		self.navigationItem.rightBarButtonItem.enabled = YES;
//		self.navigationItem.rightBarButtonItem.image   = [UIImage imageNamed:@"Button-Refresh-over.png"];
		
		[m_timerForSpinner invalidate];
		m_timerForSpinner = nil;
	}
}

- (void)beginRefreshAnimating
{
	if (!m_refreshSpinner.isAnimating) 
	{
		self.m_refreshSpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
//		CGPoint point =  self.navigationItem.rightBarButtonItem.frame;
		
//		[self.m_refreshSpinner setCenter:CGPointMake(299, 22)];
///		[[UIApplication sharedApplication].delegate.window  addSubview:self.m_refreshSpinner];
		
//		UIButton * refreshButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//		[refreshButton setFrame:CGRectMake(0, 0, 40, 30)];
		
///		[refreshButton addSubview:m_refreshSpinner];
		
		
//		self.navigationItem.rightBarButtonItem.customView = refreshButton;
		[self.m_refreshSpinner startAnimating];
		
		
		
		self.navigationItem.rightBarButtonItem.enabled = NO;
		self.navigationItem.rightBarButtonItem.image = nil;
		self.navigationItem.rightBarButtonItem.width = 100;
		
		
		if (!m_timerForSpinner) {
			self.m_timerForSpinner = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(stopRefreshAnimating) userInfo:nil repeats:NO];
		}
	}		
}

- (void)refreshButtonPressed
{
	[self beginRefreshAnimating];
}
- (void)registerBtnPressed
{
//	[self.navigationController pushViewController:m_registViewCtrl animated:YES];
	UINavigationController * registNav = [[[UINavigationController alloc] initWithRootViewController:m_registViewCtrl] autorelease];
	[self presentModalViewController:registNav animated:YES];
}
- (void)loginBtnPressed
{
	[self.navigationController pushViewController:m_loginViewCtrl animated:YES];
}
- (void)DidSelectPic:(PicCardView *)picView
{
	PhotoViewController * photoViewCtrl = [[PhotoViewController alloc] init];
	NSLog(@"[m_imgArray count] = %d",[m_imgArray count]);
	[photoViewCtrl SetImgArray:m_imgArray SelectIndex:picView.CurIndex];
	[self.navigationController pushViewController:photoViewCtrl animated:YES];
	[photoViewCtrl release];
}
- (void)setupToolbarTop {
	
	self.navigationItem.title = @"UPai";
	
	
	
	
	
//	UIBarButtonItem * refreshButton = [[UIBarButtonItem alloc] /*initWithImage:[UIImage imageNamed:@"icon-Refresh.png"]*/
//																initWithTitle:@"refresh" 																
//																style:UIBarButtonItemStyleBordered
//																target:self		
//																action:@selector(refreshButtonPressed)];

 	UIBarButtonItem * refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh 
																					target:self 
																					action:@selector(refreshButtonPressed)];
	
//	refreshButton.width = -1;
	self.navigationItem.rightBarButtonItem = refreshButton;
//	self.navigationItem.rightBarButtonItem.width = 40;
	[refreshButton release];
	
	
}
- (void)setupViewBottom
{
	self.m_bottomView = [[UIView alloc] initWithFrame:RectBottomView];
	m_bottomView.backgroundColor = [UIColor blackColor];
	m_bottomView.alpha = 0.5;
	[self.view addSubview:m_bottomView];
	
	UIButton * registerButton  = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[registerButton setFrame:RectRegisterBtn];
	[registerButton setTitle:@"regist" forState:UIControlStateNormal];
	[registerButton addTarget:self action:@selector(registerBtnPressed) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:registerButton];
	
	UIButton * loginButton  = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[loginButton setFrame:RectLoginBtn];
	[loginButton setTitle:@"login" forState:UIControlStateNormal];
	[loginButton addTarget:self action:@selector(loginBtnPressed) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:loginButton];
}

- (void)DrawSmallView
{
	int x = 0;
	int y = 0;
	
//	int lastSelectedNum = [potraitNum intValue];
	PicCardView * picCardView = nil;
	for (int i = 0; i < PIC_CNT_DEFAULT; i++) 
	{
		x = i % 4;
		y = i / 4;
		
		PicCardView * SmallView = [[PicCardView alloc] init];
		
		picCardView = SmallView;
		picCardView.delegate = self;
		
//		picCardView.backgroundColor = [UIColor redColor];
		
		picCardView.BigImg.image = [[UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg", i+1]] rescaleImageToSize:CGSizeMake(PIC_FRAME, PIC_FRAME)];
		picCardView.SmallImg.hidden = YES;
		
		picCardView.CurIndex = i;
		
		//使用tag做为头像的标记。
		picCardView.tag = i;
		
		CGRect rect = CGRectMake(XMargin+(XMargin+PIC_FRAME)*x, YMargin+(XMargin+PIC_FRAME)*y, PIC_FRAME, PIC_FRAME);

		picCardView.frame = rect;
		
		[self.m_scrollView addSubview:picCardView];
/*		if (i == lastSelectedNum) {
			self.LastSelectedSmallView = picCardView;
			self.LastSelectedSmallView.SmallImg.image = [UIImage imageNamed:@"MarkSelected.png"];
			
			[layer setBorderWidth: 2.0];
			[layer setBorderColor:[[UIColor colorWithRed:78.0/255.0 green:132.0/255.0 blue:207.0/255.0 alpha:1.0] CGColor]];//modified for 1.0.0102.101 by andrewu
			
		}
 */
	}

	
	int nTotalHeight = YMargin + (PIC_CNT_DEFAULT+3)/4*(PIC_FRAME+YMargin) + 50;
	[self.m_scrollView setContentSize:CGSizeMake(320, nTotalHeight)];
	
}

- (void)CancelFullScreen
{
	[[UIApplication sharedApplication]  setStatusBarStyle:UIStatusBarStyleDefault];
	self.navigationController.navigationBar.translucent = NO;
	[self.navigationController.view setNeedsLayout];
	self.wantsFullScreenLayout = NO;
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
	if ([viewController isKindOfClass:[UPStartViewController class]]) 
	{
		[self CancelFullScreen];
	}
}

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView 
{
	[super loadView];
	[self setupToolbarTop];
	
	self.m_scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
	[self.view addSubview:m_scrollView];
	m_scrollView.alwaysBounceVertical = YES;
	
	[self DrawSmallView];
	
	[self setupViewBottom];
	
	//prepare data source
	if (!m_imgArray) {
		self.m_imgArray = [NSMutableArray array];
		
		for (int i = 1; i <= PIC_CNT_DEFAULT; i++) 
		{
			[m_imgArray addObject:[NSString stringWithFormat:@"%d.jpg",i]];
			
		}
	}
	
	self.navigationController.delegate = self;
}


/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[m_scrollView release];
	[m_bottomView release];
	[m_refreshSpinner release];
    [super dealloc];
}


@end
